<template>
  <div>
    <div class="info-bar_2">
      <van-nav-bar
        :border="false"
        left-text="生物支付"
        left-arrow
        @click-left="$router.go(-1)"
      >
        <template #right>
          <van-icon class="emspss" name="ellipsis" />
        </template>
      </van-nav-bar>
    </div>
    <div class="main">
      <van-cell-group>
        <van-cell title="手机刷脸支付" is-link>
          <template #right-icon>
            <van-switch :value="checked" size="21" @input="onInput" />
          </template>
        </van-cell>
      </van-cell-group>
    </div>
    <van-popup v-model="show">
      <div class="facebox">
        <div class="mask"></div>
        <video ref="video" width="100%" height="200" autoplay></video>
        <canvas ref="canvas" v-show="cas" width="500" height="480"></canvas>
        <van-button
          :loading="btnload"
          class="btnsmit"
          @click="photograph"
          round
          type="info"
          >确定</van-button
        >
      </div>
    </van-popup>
  </div>
</template>

<script>
export default {
  data() {
    return {
      checked: false,
      show: false,
      cas: false,
      btnload: false,
      face: {
        GroupId: "002",
        PersonName: this.$store.state.emailLogin[0].Account,
        PersonId: "",
        Gender: 0,
        Image: "",
        QualityControl: 3,
        UniquePersonControl: 3,
      },
      isFace: "",
      facestatus: "",
      isFlag: 0,
      faceValidation: {
        pid: 0,
        Image: "",
      },
    };
  },
  mounted() {
    this.getFacepaymentStatus();
  },
  methods: {
    async getFacepaymentStatus() {
      const { data: res } = await this.$http.get("isFacePaymentOpen", {
        params: { id: this.$store.state.emailLogin[0].userID },
      });
      this.isFace = res.isface.isFace;
      this.facestatus = res.isface.facestatus;
      res.isface.facestatus == "false"
        ? (this.checked = false)
        : (this.checked = true);
      // console.log(res);
    },
    //关闭人脸
    async closePayment() {
      const { data: res } = await this.$http.post("ModifytheFaceStatus", {
        status: "false",
        id: this.$store.state.emailLogin[0].userID,
      });
      console.log(res);
      if (res.status === 200) {
        this.checked = false;
      }
    },
    onInput(checked) {
      if (checked == false) {
        this.$dialog
          .confirm({
            message: "确认关闭人脸支付吗！",
          })
          .then(() => {
            this.closePayment();
            this.checked = checked;
          });
      }
      if (checked == true) {
        if (this.isFace === "false" && this.facestatus == "false") {
          this.callCamera();
          this.show = true;
        }
        if (this.isFace === "true" && this.facestatus == "false") {
          //  打开人脸支付
          this.callCamera();
          this.show = true;
          this.isFlag = 1;
        }
      }
    },
    callCamera() {
      // H5调用电脑摄像头API
      navigator.mediaDevices
        .getUserMedia({
          video: true,
        })
        .then((success) => {
          // 摄像头开启成功
          this.$refs["video"].srcObject = success;
          // 实时拍照效果
          this.$refs["video"].play();
        })
        .catch(() => {
          console.error("摄像头开启失败，请检查摄像头是否可用！");
        });
    },
    photograph() {
      this.btnload = true;
      setTimeout(() => {
        this.btnload = false;
        let ctx = this.$refs["canvas"].getContext("2d");
        // 把当前视频帧内容渲染到canvas上
        ctx.drawImage(this.$refs["video"], 0, 0, 640, 480);
        // 转base64格式、图片格式转换、图片质量压缩
        let imgBase64 = this.$refs["canvas"].toDataURL("image/jpeg", 0.7); // 由字节转换为KB 判断大小
        console.log(imgBase64);

        if (this.isFlag === 1) {
          this.faceValidation.Image = imgBase64;
          this.faceValidation.pid =
            this.$store.state.emailLogin[0].userID.toString();
          //人脸验证
          this.FaceVerification();
        } else {
          this.face.Image = imgBase64;
          this.face.PersonId =
            this.$store.state.emailLogin[0].userID.toString();
          this.LoadFaceinfo();
        }
      }, 1200);
    },
    async LoadFaceinfo() {
      const { data: res } = await this.$http.post("UploadfaceInfo", this.face);
      console.log(res);
      if (res.status == 200) {
        this.ModifyPaymentStatus();
      }
    },
    //人脸验证
    async FaceVerification() {
      console.log("开通");
      const { data: res } = await this.$http.post(
        "FaceVerification",
        this.faceValidation
      );
      console.log(res);
      if (res.data.IsMatch == true) {
        this.openFacePayment();
      }
      if (res.data.code == "InvalidParameterValue.NoFaceInPhoto") {
        this.$toast("人脸不符！");
      }
    },
    // 打开人脸支付
    async openFacePayment() {
      const { data: res } = await this.$http.post("ModifytheFaceStatus", {
        status: "true",
        id: this.$store.state.emailLogin[0].userID,
      });
      console.log(res);
      if (res.status === 200) {
        this.$toast("开通成功！");
        this.show = false;
        this.closeCamera();
        this.isFlag = 0;
        this.checked = true;
      }
    },
    //开通人脸支付
    async ModifyPaymentStatus() {
      let id = {
        pid: this.$store.state.emailLogin[0].userID,
        id: this.$store.state.emailLogin[0].userID,
      };
      const { data: res } = await this.$http.post("ModifyPaymentStatus", id);
      console.log(res);
      if (res.status === 200) {
        this.$toast.success("开通成功！");
        this.show = false;
        this.checked = true;
        this.closeCamera();
      }
    },
    base64ImgtoFile(dataurl, filename = "file") {
      let arr = dataurl.split(",");
      let mime = arr[0].match(/:(.*?);/)[1];
      let suffix = mime.split("/")[1];
      let bstr = atob(arr[1]);
      let n = bstr.length;
      let u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], `${filename}.${suffix}`, {
        type: mime,
      });
    },
    closeCamera() {
      if (!this.$refs["video"].srcObject) return;
      let stream = this.$refs["video"].srcObject;
      let tracks = stream.getTracks();
      tracks.forEach((track) => {
        track.stop();
      });
      this.$refs["video"].srcObject = null;
    },
  },
};
</script>

<style lang="less" scoped>
.info-bar_2 {
  position: fixed;
  left: 0;
  width: 100%;
  z-index: 1200;
  .van-nav-bar {
    background-color: #96bbce;
  }
}
.main {
  position: absolute;
  width: 100%;
  top: 48px;
  left: 0;
  background-color: #f2f2f2;
  height: 100%;
}
.facebox {
  width: 250px;
  height: 250px;
  position: relative;
  .mask {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 200px;
    background: rgba(253, 253, 253, 0.5);
  }
}
.btnsmit {
  left: 30%;
  width: 120px;
  //   margin: -4px;
}
</style>